import {PHONE, PASSWORD} from '@/config/regex'
// 命名空间
const strategies = {
  isNonEmpty: function (value, errorMsg) {
    if (value === '') {
      return errorMsg
    }
  },
  isMobile: function (value, errorMsg) {
    if (!PHONE.test(value)) {
      return errorMsg
    }
  },
  minLength: function (value, length, errorMsg) {
    if (value.length < length) {
      return errorMsg
    }
  },
  isPassword: function (value, errorMsg) {
    if (!PASSWORD.test(value)) {
      return errorMsg
    }
  }
}

const Validator = function () {
  this.cache = [] // 保存校验结果
}
Validator.prototype.start = function () {
  for (let i = 0, validatorFunc; i < this.cache.length; i++) {
    validatorFunc = this.cache[i]
    let msg = validatorFunc()
    if (msg) {
      return msg
    }
  }
}
// 单个规则
Validator.prototype.add = function (ele, rule, errorMsg) {
  // console.log(ele, rule, errorMsg)
  let arr = rule.split(':')
  this.cache.push(function () {
    let strategy = arr.shift() // 选出的校验方法
    arr.unshift(ele.value) // 把input的value添加到参数列表
    arr.push(errorMsg) // 把errorMsg添加到参数列表
    return strategies[strategy].apply(ele, arr)
  })
}
// 多个规则
/* eslint-disable no-new */
Validator.prototype.adds = function (dom, rules) {
  let self = this
  console.log(dom, rules)
  for (let i = 0; i < rules.length; i++) {
  // for (let i = 0, rule; rule = rules[ i++ ];) {
    // rule = rules[i]
    (function (rule) {
      let strategyAry = rule.strategy.split(':')
      let errorMsg = rule.errorMsg
      self.cache.push(function () {
        let strategy = strategyAry.shift()
        strategyAry.unshift(dom.value)
        strategyAry.push(errorMsg)
        return strategies[strategy].apply(dom, strategyAry)
      })
    })(rules[i])
  }
}

export default Validator
